package com.unlcn.ils.wms.backend.service.inbound.impl;

import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.domain.ResultDTOWithPagination;
import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.baseDataBO.CustomerName;
import com.unlcn.ils.wms.backend.bo.baseDataBO.CustomerNameList;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsAsnTempBO;
import com.unlcn.ils.wms.backend.enums.DeleteFlagEnum;
import com.unlcn.ils.wms.backend.enums.TmsInspectStatusEnum;
import com.unlcn.ils.wms.backend.enums.WhCodeEnum;
import com.unlcn.ils.wms.backend.service.inbound.WmsInboundAsnService;
import com.unlcn.ils.wms.backend.util.BeansUtils;
import com.unlcn.ils.wms.backend.util.BrowerEncodeingUtils;
import com.unlcn.ils.wms.backend.util.DateUtils;
import com.unlcn.ils.wms.base.dto.WmsRecordsImportExcelDTO;
import com.unlcn.ils.wms.base.dto.WmsWarehouseNoticeHeadForASNListResultDTO;
import com.unlcn.ils.wms.base.mapper.additional.WmsInboundAsnExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.WmsInboundAsnOrderAddMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsWarehouseNoticeExtMapper;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrder;
import com.unlcn.ils.wms.base.model.inbound.WmsWarehouseNoticeHead;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class WmsInboundAsnServiceImpl implements WmsInboundAsnService {

    private Logger logger = LoggerFactory.getLogger(AsnOrderServiceImpl.class);

    @Autowired
    WmsInboundAsnExtMapper wmsInboundAsnExtMapper;
    @Autowired
    private WmsInboundAsnOrderAddMapper wmsInboundAsnOrderAddMapper;
    @Autowired
    private WmsWarehouseNoticeExtMapper wmsWarehouseNoticeExtMapper;


    /**
     * <p>
     * 2018-4-20 重构入库通知单  此方法新方法
     * </p>
     *
     * @param paramMap 参数封装
     */
    @Override
    public ResultDTOWithPagination<List<WmsWarehouseNoticeHeadForASNListResultDTO>> getInboundNoticeList(Map<String, Object> paramMap) throws Exception {
        Integer pageNo = Integer.valueOf(paramMap.get("pageNo").toString());
        Integer pageSize = Integer.valueOf(paramMap.get("pageSize").toString());
        Object transferDateStart = paramMap.get("asnCheckTransferDateStart");
        Object transferDateEnd = paramMap.get("asnCheckTransferDateEnd");
        Object offlineDateStart = paramMap.get("asnOfflineDateStart");
        Object offlineDateEnd = paramMap.get("asnOfflineDateEnd");
        if (transferDateStart != null && StringUtils.isNotBlank(transferDateStart.toString())) {
            paramMap.put("transferDateStart", transferDateStart + " 00:00:00");
        }
        if (transferDateEnd != null && StringUtils.isNotBlank(transferDateEnd.toString())) {
            paramMap.put("transferDateEnd", transferDateEnd + " 23:59:59");
        }
        if (offlineDateStart != null && StringUtils.isNotBlank(offlineDateStart.toString())) {
            paramMap.put("offlineDateStart", offlineDateStart + " 00:00:00");
        }
        if (offlineDateEnd != null && StringUtils.isNotBlank(offlineDateEnd.toString())) {
            paramMap.put("offlineDateEnd", offlineDateEnd + " 23:59:59");
        }

        paramMap.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        paramMap.put("orderBy", "a.wnd_id desc");
        paramMap.put("limitStart", (pageNo - 1) * pageSize < 0 ? 0 : (pageNo - 1) * pageSize);
        paramMap.put("limitEnd", pageSize);
        List<WmsWarehouseNoticeHeadForASNListResultDTO> list = wmsWarehouseNoticeExtMapper.selectNoticeListByParamForASN(paramMap);
        int count = wmsWarehouseNoticeExtMapper.countNoticeListByParamForASN(paramMap);
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(pageNo);
        pageVo.setPageSize(pageSize);
        pageVo.setTotalRecord(count);
        ResultDTOWithPagination<List<WmsWarehouseNoticeHeadForASNListResultDTO>> result = new ResultDTOWithPagination<>();
        result.setPageVo(pageVo);
        result.setData(list);
        return result;
    }

    /**
     * <p>
     * 2018-4-20 重构入库通知单  此方法过时: 新方法{@link WmsInboundAsnServiceImpl#getInboundNoticeList}
     * </p>
     *
     * @param paramMap 参数封装
     */
    @Deprecated
    @Override
    public Map<String, Object> getAsnListOld(Map<String, Object> paramMap) throws Exception {
        Map<String, Object> resultMap = Maps.newHashMap();
        Integer pageNo = Integer.valueOf(paramMap.get("pageNo").toString());
        Integer pageSize = Integer.valueOf(paramMap.get("pageSize").toString());
        if (paramMap.get("asnCheckTransferDateStart") != null
                && StringUtils.isNotBlank(paramMap.get("asnCheckTransferDateStart").toString())) {
            paramMap.put("asnCheckTransferDateStart", DateUtils.StrToDate(paramMap.get("asnCheckTransferDateStart").toString(), DateUtils.YYYY_MM_DD));
        }
        if (paramMap.get("asnCheckTransferDateEnd") != null
                && StringUtils.isNotBlank(paramMap.get("asnCheckTransferDateEnd").toString())) {
            Date asnCheckTransferDateEnd = DateUtils.StrToDate(paramMap.get("asnCheckTransferDateEnd").toString(), DateUtils.YYYY_MM_DD);
            asnCheckTransferDateEnd.setTime(asnCheckTransferDateEnd.getTime() + 24 * 3600000 - 1);
            paramMap.put("asnCheckTransferDateEnd", asnCheckTransferDateEnd);
        }
        if (paramMap.get("asnOfflineDateStart") != null
                && StringUtils.isNotBlank(paramMap.get("asnOfflineDateStart").toString())) {
            paramMap.put("asnOfflineDateStart", DateUtils.StrToDate(paramMap.get("asnOfflineDateStart").toString(), DateUtils.YYYY_MM_DD));
        }
        if (paramMap.get("asnOfflineDateEnd") != null
                && StringUtils.isNotBlank(paramMap.get("asnOfflineDateEnd").toString())) {
            Date asnOfflineDateEnd = DateUtils.StrToDate(paramMap.get("asnOfflineDateEnd").toString(), DateUtils.YYYY_MM_DD);
            asnOfflineDateEnd.setTime(asnOfflineDateEnd.getTime() + 24 * 3600000 - 1);
            paramMap.put("asnOfflineDateEnd", asnOfflineDateEnd);
        }
        paramMap.put("limitStart", (pageNo - 1) * pageSize < 0 ? 0 : (pageNo - 1) * pageSize);
        paramMap.put("limitEnd", pageSize);
        //List<Map<String, Object>> infos = wmsInboundAsnExtMapper.queryForList(paramMap);
        List<Map<String, Object>> infos = wmsInboundAsnExtMapper.queryNewForList(paramMap);
        BeansUtils beansUtils = new BeansUtils();
        List<WmsAsnTempBO> wmsAsnTempBOList = beansUtils.listMap2JavaBean(infos, WmsAsnTempBO.class);
        ArrayList<WmsAsnTempBO> resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(wmsAsnTempBOList)) {
            wmsAsnTempBOList.forEach(v -> {
                if (Objects.equals(v.getInspectStatus(), null)) {
                    v.setInspectStatus(TmsInspectStatusEnum.WAYBILL_INIT.getValue());
                }
                resultList.add(v);
            });
        }
        resultMap.put("wmsAsnTempBOQuery", paramMap);
        //paramMap.put("totalRecord", wmsInboundAsnExtMapper.queryForCount(paramMap));
        paramMap.put("totalRecord", wmsInboundAsnExtMapper.queryNewForCount(paramMap));
        resultMap.put("wmsAsnTempBO", resultList);
        return resultMap;

        /*List<WmsAsnTemp> infos = wmsInboundAsnExtMapper.queryForList(paramMap);
        List<WmsAsnTempBO> wmsAsnTempBOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(infos)) {
            infos.stream().forEach(v -> {
                WmsAsnTempBO bo = new WmsAsnTempBO();
                BeanUtils.copyProperties(v, bo);
                wmsAsnTempBOList.add(bo);
            });
            resultMap.put("wmsAsnTempBO", wmsAsnTempBOList);
        }
        resultMap.put("wmsAsnTempBOQuery", paramMap);
        paramMap.put("totalRecord",wmsInboundAsnExtMapper.queryForCount(paramMap));
        return resultMap;*/
    }

    /**
     * 查询所有的客户名称
     * <p>
     * 2018-4-23 此方法因入库通知单重构 重写
     * </p>
     *
     * @return
     */
    @Override
    public List<WmsWarehouseNoticeHead> getAllCustomerName(String whCode) {
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        params.put("whCode", whCode);
        return wmsWarehouseNoticeExtMapper.selectAllNoticeCustomerNameList(params);
    }

    /**
     * 查询所有的客户名称
     * <p>
     * 2018-4-23 此方法因入库通知单重构 重写 {@link WmsInboundAsnServiceImpl#getAllCustomerName}
     * </p>
     *
     * @return
     */
    @Override
    @Deprecated
    public List<CustomerNameList> getAllCustomerNameOld(String whCode) {
        byte del = DeleteFlagEnum.DELETED.getValue();
        List<WmsInboundOrder> wmsInboundOrders = wmsInboundAsnOrderAddMapper.selectAllCustomerName(del, whCode);
        List<CustomerNameList> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(wmsInboundOrders)) {
            for (WmsInboundOrder wmsInboundOrder : wmsInboundOrders) {
                if (!Objects.equals(wmsInboundOrder, null)) {
                    CustomerNameList nameList = new CustomerNameList();
                    CustomerName customerName = new CustomerName();
                    customerName.setName(wmsInboundOrder.getOdCustomerName());
                    nameList.setCustomerId(customerName);
                    result.add(nameList);
                }
            }
        }
        return result;
    }

    /**
     * 根据时间查询
     * <p>
     * 2018-4-23 此方法因入库通知单重构,此方法为新方法
     * </p>
     *  @param wmsAsnTempBO 参数封装
     * @param whCode       仓库code
     */
    @Override
    public List<WmsWarehouseNoticeHeadForASNListResultDTO> queryListByTime(WmsAsnTempBO wmsAsnTempBO, String whCode) {
        if (logger.isInfoEnabled()) {
            logger.info("WmsInboundAsnServiceImpl.queryListByTime wmsAsnTempBO: {}", wmsAsnTempBO);
        }
        if (wmsAsnTempBO == null) {
            throw new BusinessException("参数为空");
        }
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        if (StringUtils.isBlank(wmsAsnTempBO.getStartCreateTime()) && StringUtils.isBlank(wmsAsnTempBO.getEndCreateTime())) {
            throw new BusinessException("请至少选择一项时间");
        }
        HashMap<String, Object> params = Maps.newHashMap();
        wmsAsnTempBO.setStartCreateTime(wmsAsnTempBO.getStartCreateTime() + " 00:00:00");
        wmsAsnTempBO.setEndCreateTime(wmsAsnTempBO.getEndCreateTime() + " 23:59:59");
        params.put("startCreateTime", wmsAsnTempBO.getStartCreateTime());
        params.put("endCreateTime", wmsAsnTempBO.getEndCreateTime());
        params.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        params.put("whCode", whCode);
        params.put("orderBy", "a.wnd_id desc");
        return wmsWarehouseNoticeExtMapper.selectNoticeListByParamForASN(params);
    }


    /**
     * 根据时间查询
     * <p>
     * 2018-4-23 此方法因入库通知单重构,此方法过时{@link WmsInboundAsnService#queryListByTime}
     * </p>
     *
     * @param wmsAsnTempBO 参数封装
     */
    @Override
    @Deprecated
    public List<WmsAsnTempBO> queryListByTimeOld(WmsAsnTempBO wmsAsnTempBO) throws Exception {
        logger.info("WmsInboundAsnServiceImpl.queryListByTimeOld wmsAsnTempBO: {}", wmsAsnTempBO);
        if (wmsAsnTempBO == null) {
            throw new BusinessException("参数为空");
        }
        if (StringUtils.isBlank(wmsAsnTempBO.getStartCreateTime()) || StringUtils.isBlank(wmsAsnTempBO.getEndCreateTime())) {
            return null;
        }
        wmsAsnTempBO.setStartCreateTime(wmsAsnTempBO.getStartCreateTime() + " 00:00:00");
        wmsAsnTempBO.setEndCreateTime(wmsAsnTempBO.getEndCreateTime() + " 23:59:59");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("startCreateTime", wmsAsnTempBO.getStartCreateTime());
        paramMap.put("endCreateTime", wmsAsnTempBO.getEndCreateTime());
        List<Map<String, Object>> infos = wmsInboundAsnExtMapper.queryNewForListByTime(paramMap);
        BeansUtils beansUtils = new BeansUtils();
        List<WmsAsnTempBO> wmsAsnTempBOList = beansUtils.listMap2JavaBean(infos, WmsAsnTempBO.class);
        List<WmsAsnTempBO> resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(wmsAsnTempBOList)) {
            wmsAsnTempBOList.forEach(v -> {
                if (Objects.equals(v.getInspectStatus(), null)) {
                    v.setInspectStatus(TmsInspectStatusEnum.WAYBILL_INIT.getValue());
                    resultList.add(v);
                }
            });
        }
        return resultList;
    }

    /**
     * 入库记录导出功能
     * <p>
     * 2018-1-22 新需求 (君马库)入库记录查询页面增加“物料代码”、“物料名称”、“颜色代码”、“颜色”字段显示，导出的文件中也需要包含这四个字段；
     * </p>
     *
     * @param dto      参数封装对象
     * @param request  请求体
     * @param response @throws Exception
     */
    @Override
    public void updateInboundImportExcel(WmsRecordsImportExcelDTO dto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("WmsInboundAsnServiceImpl.updateInboundImportExcel param: {}", dto);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //校验
        checkImport(dto);
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(dto.getRecieveStartTime());
            endTime = sdf.parse(dto.getRecieveEndTime());
            endTime.setTime(endTime.getTime() + 24 * 3600 * 1000 - 1);
        } catch (ParseException e) {
            logger.error("WmsInboundAsnServiceImpl.updateInboundImportExcel param{}", e);
            throw new BusinessException("传入的时间格式错误:yyyy-MM-dd");
        }
        if (!Objects.equals(startTime, null) && !Objects.equals(endTime, null)) {
            HashMap<String, Object> paramMap = Maps.newHashMap();
            //paramMap.put("consigneeStartDate", sdf.format(startTime));
            //paramMap.put("consigneeEndDate", sdf.format(endTime));
            paramMap.put("rk_start_date", startTime);
            paramMap.put("rk_end_date", endTime);
            paramMap.put("orderByClause", "rkDate desc");
            paramMap.put("odWhCode", dto.getWhCode());
            //分仓库进行记录导出
            List<Map<String, Object>> recordList = null;
            String[] hearders = null;
            //设置值
            HSSFWorkbook workbook = null;
            if (WhCodeEnum.JM_CS.getValue().equals(dto.getWhCode()) || WhCodeEnum.JM_XY.getValue().equals(dto.getWhCode())) {
                recordList = wmsInboundAsnOrderAddMapper.selectInboundRecordImportExcelForJM(paramMap);
                if (CollectionUtils.isEmpty(recordList)) {
                    throw new BusinessException("未查询到对应时间段的收货记录");
                }
                //1.导出excel头
                hearders = new String[]{
                        "车架号(VIN码)", "车型", "物料代码", "物料名称", "颜色代码", "颜色",
                        "收货完成时间", "入库确认时间", "收货操作人", "入库确认人", "位置"
                };
                //设置值
                workbook = updateExportToExcelForJM("入库记录数据导出", hearders, recordList, "yyyy-MM-dd HH:mm:ss");

            }
            if (WhCodeEnum.UNLCN_XN_CQ.getValue().equals(dto.getWhCode())) {
                wmsInboundAsnOrderAddMapper.updateSetSQLMode();
                recordList = wmsInboundAsnOrderAddMapper.selectInboundRecordImportExcelForCQ(paramMap);
                if (CollectionUtils.isEmpty(recordList)) {
                    throw new BusinessException("未查询到对应时间段的收货记录");
                }
                //1.导出excel头
                hearders = new String[]{
                        "车架号(VIN码)", "车型", "收货完成时间", "入库确认时间", "收货操作人", "入库确认人", "位置"
                };
                //设置值
                workbook = updateExportToExcelForCQ("入库记录数据导出", hearders, recordList, "yyyy-MM-dd HH:mm:ss");
            }
            if (workbook != null) {


                //输出流--提供下载
                BufferedOutputStream bufferedOutputStream = null;
                BufferedInputStream bufferedInputStream = null;
                ByteArrayOutputStream bos = null;
                ByteArrayInputStream inputStream = null;
                ServletOutputStream outputStream = null;
                try {
                    bos = new ByteArrayOutputStream(1024);
                    workbook.write(bos);
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                    response.setHeader("Content-disposition", BrowerEncodeingUtils.getContentDisposition("InboundRecordImportExcel.xls", request));
                    inputStream = new ByteArrayInputStream(bos.toByteArray());
                    outputStream = response.getOutputStream();
                    bufferedOutputStream = new BufferedOutputStream(outputStream);
                    bufferedInputStream = new BufferedInputStream(inputStream);
                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                    }
                } catch (IOException e) {
                    logger.error("WmsInboundAsnServiceImpl.updateInboundImportExcel error:", e);
                    throw new BusinessException("下载文件异常!");
                } finally {
                    if (bufferedInputStream != null) {
                        bufferedInputStream.close();
                    }
                    if (bufferedOutputStream != null) {
                        bufferedOutputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                    if (workbook != null) {
                        workbook.close();
                    }
                }

            }
        }
    }

    /**
     * 判断导出数据条数
     *
     * @param dto 参数封装
     * @return 返回值
     * @throws Exception 异常
     */
    @Override
    public Integer countInboundRecord(WmsRecordsImportExcelDTO dto) throws Exception {
        logger.info("WmsInboundAsnServiceImpl.updateInboundImportExcel param: {}", dto);
        //校验
        checkImport(dto);
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = checkDateTime(dto.getRecieveStartTime());
            endTime = checkDateTime(dto.getRecieveEndTime());
        } catch (Exception e) {
            logger.error("WmsInboundAsnServiceImpl.updateInboundImportExcel param{}", e);
            throw new BusinessException("传入的时间格式错误:yyyy-MM-dd");
        }
        if (startTime != null && endTime != null) {
            HashMap<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("consigneeStartDate", dto.getRecieveStartTime());
            paramMap.put("consigneeEndDate", dto.getRecieveEndTime());
            paramMap.put("odWhCode", dto.getWhCode());
            return wmsInboundAsnOrderAddMapper.countInboundRecord(paramMap);
        }
        return null;
    }

    private void checkImport(WmsRecordsImportExcelDTO dto) {
        if (Objects.equals(dto, null)) {
            throw new BusinessException("传入参数不能为空!");
        }
        if (StringUtils.isBlank(dto.getUserId())) {
            throw new BusinessException("传入用户Id不能为空!");
        }
        if (StringUtils.isBlank(dto.getWhCode())) {
            throw new BusinessException("传入的仓库Code不能为空");
        }
        if (StringUtils.isBlank(dto.getRecieveStartTime())) {
            throw new BusinessException("传入的收货起始时间不能为空!");
        }
        if (StringUtils.isBlank(dto.getRecieveEndTime())) {
            throw new BusinessException("传入的收货截止时间不能为空!");
        }
    }

    private Date checkDateTime(String dateStr) throws Exception {
        return DateUtils.StrToDate(dateStr, DateUtils.YYYY_MM_DD);
    }

    /**
     * @param title             sheet标题
     * @param headers           表头
     * @param wmsInboundRecords 入库记录
     * @param pattern           @Title exportExcel
     */
    private HSSFWorkbook updateExportToExcelForCQ(String title, String[] headers,
                                                  List<Map<String, Object>> wmsInboundRecords, String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = getRows(title, workbook);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFCellStyle style2 = getHssfCellStyle(workbook, style);
        //// 声明一个画图的顶级管理器
        //HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        //// 定义注释的大小和位置,详见文档
        //HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
        //        0, 0, 0, (short) 4, 2, (short) 6, 5));
        //// 设置注释内容
        //comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
        //// 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
        //comment.setAuthor("leno");

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据，产生数据行
        Iterator<Map<String, Object>> iterator = wmsInboundRecords.iterator();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        int index = 0;
        while (iterator.hasNext()) {
            index++;
            row = sheet.createRow(index);//创建行
            Map<String, Object> next = iterator.next();
            //对应头  设置cell的值
            for (short i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                switch (i) {
                    case 0: {
                        //"车架号(VIN码)"
                        cell.setCellValue(updateSetCellValue(next.get("odd_vin")));
                        break;
                    }
                    case 1: {
                        // "车型"
                        cell.setCellValue(updateSetCellValue(next.get("odd_vehicle_spec_name")));
                        break;
                    }
                    case 2: {
                        //"收货完成时间"
                        cell.setCellValue(updateSetCellValue(getFormatDate((Date) next.get("od_consignee_date"))));
                        break;
                    }
                    case 3: {
                        //"入库确认时间"
                        cell.setCellValue(updateSetCellValue(getFormatDate((Date) next.get("rkDate"))));
                        break;
                    }
                    case 4: {
                        //"收货操作人"
                        cell.setCellValue(updateSetCellValue(next.get("od_consignee_name")));
                        break;
                    }
                    case 5: {
                        //"入库确认人"
                        cell.setCellValue(updateSetCellValue(next.get("inboundConfirmUser")));
                        break;
                    }
                    case 6: {
                        //"位置"
                        cell.setCellValue(updateSetCellValue(next.get("od_wh_name"))
                                + updateSetCellValue(next.get("odd_wh_zone_name"))
                                + updateSetCellValue(next.get("odd_wh_loc_code")));
                        break;
                    }
                    default:
                        break;
                }
            }
        }
        return workbook;
    }

    private HSSFSheet getRows(String title, HSSFWorkbook workbook) {
        return workbook.createSheet(title);
    }

    /**
     * @param title             sheet标题
     * @param headers           表头
     * @param wmsInboundRecords 入库记录
     * @param pattern           @Title exportExcel
     */
    private HSSFWorkbook updateExportToExcelForJM(String title, String[] headers,
                                                  List<Map<String, Object>> wmsInboundRecords, String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFCellStyle style2 = getHssfCellStyle(workbook, style);
        //// 声明一个画图的顶级管理器
        //HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        //// 定义注释的大小和位置,详见文档
        //HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
        //        0, 0, 0, (short) 4, 2, (short) 6, 5));
        //// 设置注释内容
        //comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
        //// 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
        //comment.setAuthor("leno");

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据，产生数据行
        Iterator<Map<String, Object>> iterator = wmsInboundRecords.iterator();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        int index = 0;
        while (iterator.hasNext()) {
            index++;
            row = sheet.createRow(index);//创建行
            Map<String, Object> next = iterator.next();
            //对应头  设置cell的值
            for (short i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                switch (i) {
                    case 0: {
                        //"车架号(VIN码)"
                        cell.setCellValue(updateSetCellValue(next.get("odd_vin")));
                        break;
                    }
                    case 1: {
                        // "车型"
                        cell.setCellValue(updateSetCellValue(next.get("odd_vehicle_spec_name")));
                        break;
                    }
                    case 2: {
                        //"物料代码"
                        cell.setCellValue(updateSetCellValue(next.get("odd_material_code")));
                        break;
                    }
                    case 3: {
                        //"物料名称"
                        cell.setCellValue(updateSetCellValue(next.get("odd_material_name")));
                        break;
                    }
                    case 4: {
                        //"颜色代码"
                        cell.setCellValue(updateSetCellValue(next.get("odd_car_colour_code")));
                        break;
                    }
                    case 5: {
                        //"颜色"
                        cell.setCellValue(updateSetCellValue(next.get("odd_car_colour")));
                        break;
                    }
                    case 6: {
                        //"收货完成时间"
                        cell.setCellValue(updateSetCellValue(getFormatDate((Date) next.get("od_consignee_date"))));
                        break;
                    }
                    case 7: {
                        //"入库确认时间"
                        cell.setCellValue(updateSetCellValue(getFormatDate((Date) next.get("rkDate"))));
                        break;
                    }
                    case 8: {
                        //"收货操作人"
                        cell.setCellValue(updateSetCellValue(next.get("od_consignee_name")));
                        break;
                    }
                    case 9: {
                        //"入库确认人"
                        cell.setCellValue(updateSetCellValue(next.get("inboundConfirmUser")));
                        break;
                    }
                    case 10: {
                        //"位置"
                        cell.setCellValue(updateSetCellValue(next.get("od_wh_name"))
                                + updateSetCellValue(next.get("odd_wh_zone_name"))
                                + updateSetCellValue(next.get("odd_wh_loc_code")));
                        break;
                    }
                    default:
                        break;
                }
            }
        }
        return workbook;
    }

    /**
     * 设置样式
     *
     * @param workbook 工作簿
     * @param style    样式
     * @return 返回值
     */
    private HSSFCellStyle getHssfCellStyle(HSSFWorkbook workbook, HSSFCellStyle style) {
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.WHITE.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        return style2;
    }

    /**
     * 判断字符串设置值--非空过滤
     *
     * @param object 传入参数
     * @return 返回值
     */
    private String updateSetCellValue(Object object) {
        if (!Objects.equals(object, null)) {
            String value = object.toString();
            if (StringUtils.isNotBlank(value)) {
                return value;
            }
        }
        return "";
    }

    /**
     * 时间格式化--非空过滤
     *
     * @param date
     * @return
     */
    private String getFormatDate(Date date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (date != null) {
            return sdf.format(date);
        }
        return "";
    }
}
